<template>
	<div>
		<div class="box">
			<el-form
				:model="formData"
				ref="form"
				:inline="false"
				label-width="5px"
				size="normal"
				:hide-required-asterisk="true">
				<el-table
					:header-cell-class-name="setHeaderCellName"
					ref="multipleTable"
					:data="formData.tmlSupplementList"
					tooltip-effect="dark"
					style="width: 100%">
					<TableCloumn
						v-for="item in tableCloumns"
						:state="state"
						:cellOptions="item"
						dataName="tmlSupplementList"
						minWidth="150px"></TableCloumn>

					<!-- <el-table-column -->
					<!-- label="操作" -->
					<!-- width="100" -->
					<!-- align="center" -->
					<!-- fixed="left" -->
					<!-- > -->
					<!-- <template slot-scope="scope"> -->
					<!-- <div> -->
					<!-- <el-button -->
					<!-- type="text" -->
					<!-- @click=" -->
					<!-- remove( -->
					<!-- scope.$index, -->
					<!-- scope.row, -->
					<!-- formData.tmlSupplementList -->
					<!-- ) -->
					<!-- " -->
					<!-- >删除</el-button -->
					<!-- > -->
					<!-- </div> -->
					<!-- </template> -->
					<!-- </el-table-column> -->
				</el-table>
			</el-form>
			<!-- <div class="btn" @click="add(formData.tmlSupplementList)"> -->
			<!-- <i class="el-icon-plus"></i> -->
			<!-- <span>增加一行</span> -->
			<!-- </div> -->
		</div>
	</div>
</template>

<script>
	import * as apis from '@/api/quota/forecast/edit/api.js';
	import TableCloumn from '@/views/finance/manage/tableColumn/index.vue';
	export default {
		components: { TableCloumn },
		props: {
			value: {
				required: false,
			},
			state: {
				required: false,
			},
			type: {
				required: false,
			},
		},
		data() {
			return {};
		},
		inject: ['details_forecast'],
		computed: {
			details() {
				return this.details_forecast();
			},
			formData: {
				get() {
					// return this.value;
					return this.useVModel.call(this);
				},
				set(val) {
					this.$emit('input', val);
				},
			},

			tableCloumns() {
				return [
					{
						label: '产品',
						prop: 'schemeName',
						type: 'input',
						state: 'readonly',
					},
					{
						label: '车型',
						prop: 'carModelName',
						type: 'input',
						state: 'readonly',
					},
					{
						label: '利率（%）',
						prop: 'interestRate',
						type: 'input_number',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '车价',
						prop: 'purchasePrice',
						type: 'input_number',
						state: 'readonly',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},

					{
						label: '购置税',
						prop: 'carPurchaseTax',
						type: 'input_number',
						tag: 'price',
						watch: ({ val, row }) => {
							let price = row.purchasePrice;
							if (val) {
								price = this.toNumberAdd(
									val,
									row.purchasePrice,
								);
							}
							this.$set(row, 'carTotlePrice', price);
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					// {
					// 	label: '首年保险',
					// 	prop: 'firstYearInsurance',
					// 	type: 'input_number',
					// 	state: 'readonly',
					// 	tag: 'price',
					// },
					// {
					// 	label: '上牌费',
					// 	prop: 'carLicensePrice',
					// 	type: 'input_number',
					// 	state: 'readonly',
					// 	tag: 'price',
					// },
					{
						label: '总额',
						prop: 'carTotlePrice',
						type: 'input_number',
						state: 'readonly',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '首付比例（%）',
						prop: 'downpaymentProportion',
						type: 'input_number',
						max: 100,
						rules: true,
						event: {
							type: 'blur',
							cb: row => {
								let price = this.numberRide(
									row.downpaymentProportion / 100,
									row.purchasePrice,
								)?.toFixed?.(2);
								if (Number.isFinite(price * 1)) {
									this.$set(row, 'downpayment', price);
								} else {
									this.$set(row, 'downpayment', undefined);
								}
							},
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '首付',
						prop: 'downpayment',
						type: 'input_number',
						tag: 'price',
						state: 'readonly',
						watch: ({ val, row }) => {
							let price = this.toNumberSub(
								row.carTotlePrice,
								row.downpayment,
							);
							if (Number.isFinite(price)) {
								this.$set(
									row,
									'financedAmount',
									price.toFixed?.(2),
								);
							} else {
								this.$set(row, 'financedAmount', undefined);
							}
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '融资额',
						prop: 'financedAmount',
						type: 'input_number',
						tag: 'price',
						state: 'readonly',
						watch: async ({ row }) => {
							await this.getPMT(row);
							this.setInterest(row);
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '期限（月）',
						prop: 'planTenancy',
						type: 'input_number',
						rules: true,
						watch: async ({ row }) => {
							await this.getPMT(row);
							this.setInterest(row);
						},
						prototype: {
							step: 1,
							stepStrictly: true,
						},
					},
					{
						label: '尾款比例（%）',
						prop: 'balancepaymentProportion',
						type: 'input_number',
						max: 100,
						rules: true,
						event: {
							type: 'blur',
							cb: row => {
								let price = this.numberRide(
									row.balancepaymentProportion / 100,
									row.purchasePrice,
								)?.toFixed?.(2);
								if (Number.isFinite(price * 1)) {
									this.$set(row, 'balancepayment', price);
								} else {
									this.$set(row, 'balancepayment', undefined);
								}
							},
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '尾款',
						prop: 'balancepayment',
						type: 'input_number',
						state: 'readonly',
						tag: 'price',
						watch: async ({ row }) => {
							await this.getPMT(row);
							this.setInterest(row);
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '月租金',
						prop: 'rent',
						type: 'input_number',
						state: 'readonly',
						tag: 'price',
						watch: ({ row }) => {
							this.setInterest(row);
						},
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
					{
						label: '利息',
						prop: 'interest',
						type: 'input_number',
						state: 'readonly',
						tag: 'price',
						prototype: {
							step: 0.01,
							stepStrictly: true,
						},
					},
				];
			},
		},
		async created() {
			this.formData.tmlSupplementList ??= [];
			let list = this.formData.tmlSupplementList;

			// for (let index = 0; index < list.length; index++) {
			// 	let element = list[index];
			// 	await this.getPMT(element);
			// }
		},
		mounted() {},
		methods: {
			valid() {
				return new Promise(async resolve => {
					let result = true;
					let refs = Object.values(this.$refs);
					for (let index = 0; index < refs?.length; index++) {
						const ref = refs[index];
						if (
							Object.prototype.toString.call(ref) ==
							'[object Array]'
						) {
							for (let i = 0; i < ref.length; i++) {
								const element = ref[i];
								if (element?.valid) {
									let rc = await element?.valid?.();
									result = result && rc;
								}
								if (element?.validate) {
									let rf = await this._valid(ref);
									result = result && rf;
								}
								if (element?.form_validate) {
									let rf = await this._valid(
										ref,
										'form_validate',
									);
									result = result && rf;
								}
							}
						} else {
							if (ref?.valid) {
								let rc = await ref?.valid?.();
								result = result && rc;
							}
							if (ref?.validate) {
								let rf = await this._valid(ref);
								result = result && rf;
							}
							if (ref?.form_validate) {
								let rf = await this._valid(
									ref,
									'form_validate',
								);
								result = result && rf;
							}
						}
					}

					resolve(result);
				});
			},
			setInterest(row) {
				console.log('setInterest');
				let rent = this.toNumberRide(row.rent, row.planTenancy);
				let rent1 = this.toNumberAdd(rent, row.balancepayment);
				let price = this.toNumberSub(rent1, row.financedAmount);
				if (Number.isFinite(Number(price))) {
					this.$set(
						row,
						'interest',
						Number(Number(price)?.toFixed?.(2)),
					);
				} else {
					this.$set(row, 'interest', undefined);
				}
			},
			getPMT(row) {
				console.log('getPMT');
				return new Promise(resolve => {
					let item = this.details?.productList?.find(e => {
						return e.productId == row.schemeProductId;
					});
					let params = {
						// 利率 %
						rate: row?.interestRate,
						// 期限（月）
						nper: row?.planTenancy,
						// 融资额
						pv: row?.financedAmount,
						// 尾款
						fv: row?.balancepayment ?? 0,
						// 支付时间：先付后幅
						type:
							item?.plan?.planPaymentMethodType == '1'
								? '1'
								: item?.plan?.planPaymentMethodType == '2'
								? '0'
								: '0',
					};
					let pass = true;
					for (const [key, value] of Object.entries(params)) {
						if (this.Empty(value)) {
							console.warn('key:' + key, 'value:' + value);
							pass = false;
							resolve();
							return;
						}
					}
					if (pass == false) {
						resolve();
						return;
					}
					apis?.CalcPmt(params)
						.then(res => {
							if (res.code == 200) {
								this.$set(row, 'rent', res.data?.toString());
							}
						})
						.finally(() => {
							resolve();
						});
				});
			},
			remove(index, row, list) {
				// let label = this.dict.type.quota_fee.find(
				//     (item) => item.value == row.feeKey
				// )?.label;
				this.$confirm(`此操作将删除该项, 是否继续?`, '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning',
				})
					.then(() => {
						list.splice(index, 1);
					})
					.catch(() => {});
			},
			add(list) {
				list.push({});
			},
			setHeaderCellName({ row, column, rowIndex, columnIndex }) {
				let itemConfig = this.tableCloumns?.find(
					e => e.label === column.label,
				);

				if (
					'type' in itemConfig &&
					itemConfig.type !== 'text' &&
					'rules' in itemConfig
				) {
					return 'ruleHeaderCell';
				} else {
					return '';
				}
			},
		},
	};
</script>

<style lang="scss" scoped>
	.box {
		margin: 20px;
		padding: 20px;
		border-radius: 8px;
		background-color: #fff;
		.title {
			font-size: 16px;
			font-family: PingFangSC, PingFang SC;
			font-weight: 500;
			color: #333333;
			line-height: 22px;
			padding-bottom: 15px;
			border-bottom: 1px solid #e9e9e9;
		}
	}
	.btn {
		display: flex;
		justify-content: center;
		align-items: center;
		height: 48px;
		background: #ffffff;
		border-radius: 4px;
		border: 1px solid #dadada;
		color: #1890ff;
		margin-top: 15px;
		font-size: 14px;
		cursor: pointer;
	}
</style>
